<?php

namespace app\home\controller;

use app\BaseController;
use app\home\lib\WeiXin;
use think\App;
use think\facade\Db;

use app\home\validate\Login as Logins;
use think\exception\ValidateException;

class Login extends BaseController
{
    /**
     * @name: 获取用户信息
     * @test: test font
     * @msg:
     * @param {type}
     * @return:
     */
    public function login(WeiXin $weiXin)
    {
        $code = input("code", '');
        $encryptedData = input("encryptedData", '');
        $iv = input("iv", '');
        if (!$code || !$encryptedData || !$iv) return outputJson(100, '参数缺失');
        //获取SESSION信息
        $sessionKey = $weiXin->jscode2session($code);
        dump($sessionKey);
        //返回错误信息
        if (!isset($sessionKey['session_key']) || !isset($sessionKey['openid'])) {
            return outputJson(1001, '获取session_key失败');
        }
        $userInfo = $weiXin->getUserInfo($encryptedData, $iv, $sessionKey['session_key']);
        dump($userInfo);
        //获取到用户openid
        $openid = $sessionKey['openid'];
        return outputJson(1000, 'ok', $openid);
    }

    //区域比较
    public function regionalComparison()
    {
        $post = input('post.');
        $auth = Db::name('system_admin')->where(['id' => $post['venues_id']])->field('id,lat,lng')->find();
        $distance = $this->distance($post['lat'], $post['lng'], $auth['lat'], $auth['lng']);
        return outputJson(1000, 'ok', ['distance' => $distance]);
    }

    /**
     * @param $lat1 纬度
     * @param $lon1 经度
     * @param $lat2 纬度
     * @param $lon2 经度
     * @param float $radius 星球半径 KM
     * @return float
     */
    private function distance($lat1, $lon1, $lat2, $lon2, $radius = 6378.137)
    {
        $rad = floatval(M_PI / 180.0);
        $lat1 = floatval($lat1) * $rad;
        $lon1 = floatval($lon1) * $rad;
        $lat2 = floatval($lat2) * $rad;
        $lon2 = floatval($lon2) * $rad;
        $theta = $lon2 - $lon1;
        $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));
        if ($dist < 0) {
            $dist += M_PI;
        }
        return $dist = $dist * $radius;
    }

    //信息录入
    public function infoEntry()
    {
        $post = input('post.');
        try {
            validate(Logins::class)->check($post);
        } catch (ValidateException $e) {
            return outputJson(1001, $e->getError());
        }
        $user = Db::name('user')->where(['name' => $post['name'], 'mobile' => $post['mobile'], 'id_card' => $post['id_card']])->find();
        if ($user) {
            return outputJson(1003, '信息已存在，请勿重复提交');
        }
        $userInfo = [
            'name' => $post['name'],
            'mobile' => $post['mobile'],
            'id_card' => $post['id_card'],
            'sex' => $post['sex'],
            'unit' => $post['unit'],
            'section' => $post['section'],
            'images' => $post['images'],
            'venues_id' => $post['venues_id'],
            'create_time' => date('Y-m-d H:i:S'),
            'update_time' =>  date('Y-m-d H:i:S')
        ];

        $result = Db::name('user')->insert($userInfo);
        if ($result) {
            return outputJson(1000, '保存成功');
        }
        return outputJson(1001, '保存失败');
    }
    
    //图片上传
    public function uplodeImage(){
        $file = request()->file('file');
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('public')->putFile('file', $file);
        $result = txcossc($savename, public_path() . 'public/' . $savename);
        return outputJson(1001,'fail',['url'=>$result['url']]);
    }
    
     //人脸识别
    public function searchFaces(){
        $file = request()->file('file');
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('public')->putFile('file', $file);
        //        $result = txcossc($savename, public_path() . 'public/' . $savename);
        //        dump($savename);exit;
        //获取文件路径
        $path = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME'] .'/'.$savename;
        $tencentcloud = new \Tencentcloud();
        $tencentcloud = $tencentcloud->searchFaces($path);
        if($tencentcloud['code'] == 1){
            $token = md5(time());
            $result = Db::name('user')->where(['mobile'=>$tencentcloud['mobile']])->update(['token'=>$token]);
            if($result !== false){
                return outputJson(1001, '认证成功',['token'=>$token]);
            }
        }
        return outputJson(1001, $tencentcloud['message']);
    }

}
